package com.push.spider.spider;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.push.common.config.TransConfig;
import com.push.common.manager.BeanManager;
import com.push.common.utils.*;
import com.push.common.utils.httpclient.HttpClientUtil;
import com.push.spider.utils.UrlUtils;
import com.push.web.domain.BizArticle;
import com.push.web.domain.BizSource;
import com.push.web.service.IBizArticleService;
import com.push.web.service.IBizSourceService;
import com.rometools.rome.feed.synd.SyndEntry;
import com.rometools.rome.feed.synd.SyndFeed;
import com.rometools.rome.io.SyndFeedInput;
import com.rometools.rome.io.XmlReader;
import lombok.SneakyThrows;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import us.codecraft.webmagic.selector.Html;
import us.codecraft.webmagic.selector.Selectable;

import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RSSSpider {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    private BizSource bizSource;

    @Autowired
    IBizSourceService sourceService = BeanManager.getBean(IBizSourceService.class);

    @Autowired
    IBizArticleService articleService = BeanManager.getBean(IBizArticleService.class);

    @Autowired
    private TransConfig transConfig = BeanManager.getBean(TransConfig.class);

    public int size = 0;

    public RSSSpider(String sourceId) {
        this.bizSource = sourceService.selectBizSourceBySourceId(Long.valueOf(sourceId));
    }

    @SneakyThrows
    public void run(){
        XmlReader reader = new XmlReader(new URL(bizSource.getSpiderUrl()));
        SyndFeed feed = new SyndFeedInput().build(reader);
        for (SyndEntry entry : feed.getEntries()) {
            String dataKey = EncryptUtil.encrypt(entry.getLink(), "md5");
            String title = entry.getTitle();
            String content = "";
            if (entry.getContents().size() > 0){
                content = entry.getContents().get(0).getValue();
            }
            String summary = "";
            if(null != entry.getDescription()){
                summary = entry.getDescription().getValue();
            }
            String publishTime = "", publishFormatTime = "";
            if (StringUtils.isNotNull(entry.getPublishedDate())){
                publishTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, entry.getPublishedDate());
                publishFormatTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, entry.getPublishedDate());
            }

            if (StringUtils.isEmpty(publishTime) && StringUtils.isNotNull(entry.getUpdatedDate())){
                publishTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, entry.getPublishedDate());
                publishFormatTime = DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, entry.getPublishedDate());
            }

            String url = entry.getLink();
            /*
             * 单独获取图片
             */
            String avator = "";
            Html html = new Html(content);
            List<Selectable> imgNodes = html.xpath("//img/@src").nodes();
            if (imgNodes.size() > 0) {
                avator = UrlUtils.buildUrl(url, imgNodes.get(0).toString());
            }
            BizArticle article = buildArticle(dataKey, avator, title, content, summary, publishTime, publishFormatTime, url, bizSource.getSourceId());
            BizArticle bizArticle = articleService.selectBizArticleByDataKey(dataKey);
            if (StringUtils.isNull(bizArticle)){
                //自动翻译标题
                if (StringUtils.isContainsChinese(article.getTitleOrg())){
                    article.setTitleCn(article.getTitleOrg());
                } else {
                    String transWord = getTransResult(article.getTitleOrg(), "auto", "zh");
                    JSONObject titleObj = JSONObject.parseObject(transWord);
                    JSONArray titleArray = titleObj.getJSONArray("trans_result");
                    if (StringUtils.isNotNull(titleArray) && titleArray.size() > 0){
                        article.setTitleCn(titleArray.getJSONObject(0).getString("dst"));
                    }
                }

                //自动翻译摘要
                if(transConfig.isAbstractTrans() && StringUtils.isNotEmpty(article.getSummaryOrg())){
                    String transWord = getTransResult(article.getSummaryOrg(), "auto", "zh");
                    JSONObject titleObj = JSONObject.parseObject(transWord);
                    JSONArray titleArray = titleObj.getJSONArray("trans_result");
                    if (StringUtils.isNotNull(titleArray) && titleArray.size() > 0){
                        article.setSummaryCn(titleArray.getJSONObject(0).getString("dst"));
                    }
                }

                articleService.insertBizArticle(article);
            } else {
                article.setId(bizArticle.getId());
                articleService.updateBizArticle(article);
            }
            size++;
        }
    }

    public BizArticle buildArticle(String dataKey, String avator, String title, String content,String summary, String publishTime,String publishFormatTime, String url, long sourceId){
        BizArticle article = new BizArticle();
        article.setDataKey(dataKey);
        article.setAvator(avator);
        article.setTitleOrg(title);
        article.setUrl(url);
        article.setContentsOrg(content);
        article.setSummaryOrg(summary);
        article.setPublishTime(publishTime);
        article.setPublishFormatTime(publishFormatTime);
        article.setSourceId(sourceId);
        article.setCreateTime(DateUtils.getNowDate());
        return article;
    }

    public String getTransResult(String query, String from, String to) {
        Map<String, String> params = buildParams(query, from, to);
        return HttpClientUtil.doGet(transConfig.getTransUrl(), params,false).getContent();
    }

    private Map<String, String> buildParams(String query, String from, String to) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);
        params.put("appid", transConfig.getAppid());
        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);
        // 签名
        String src = transConfig.getAppid() + query + salt + transConfig.getSecurityKey();
        params.put("sign", MD5.md5(src));
        return params;
    }

    public int getSize(){
        return size;
    }
}
